package com.lamber.framework.web;

import com.lamber.framework.exception.AuthException;
import com.lamber.framework.exception.BusinessException;
import com.lamber.framework.exception.ProcessException;
import com.lamber.framework.exception.ValidationException;
import com.lamber.framework.response.ResponseMessage;
import com.lamber.framework.util.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice(
        annotations = {RestController.class, ResponseBody.class}
)
@Order(9)
public class GlobalRestExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public GlobalRestExceptionHandler() {
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    ResponseMessage handleException(Exception exception) {
        int code = 500;
        String message;
        if (exception instanceof ProcessException) {
            ProcessException authcException = (ProcessException) exception;
            code = authcException.getStatus();
        } else if (exception instanceof AuthException) {
            AuthException authcException = (AuthException) exception;
            code = authcException.getStatus();
        } else if (exception instanceof ValidationException) {
            ValidationException validationException = (ValidationException) exception;
            code = validationException.getStatus();
        } else if (exception instanceof BusinessException) {
            BusinessException businessException = (BusinessException) exception;
            code = businessException.getStatus();
        } else {
            this.logger.error("未知错误:", exception);
        }
        message = UtilException.getBootMessage(exception);
        return ResponseMessage.error(code, message);
    }
}